﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using SHDocVw;
using System.Diagnostics;
using mshtml;

namespace AppleAutoBuy.Common
{
    public static class Util
    {
        #region Const

        const uint KEYEVENTF_EXTENDEDKEY = 0x1;
        const uint KEYEVENTF_KEYUP = 0x2;
       
        public static int SMTO_ABORTIFHUNG = 0x2;
        public static Guid IID_IHTMLDocument = new Guid("626FC520-A41E-11CF-A731-00A0C9082637");
        
        #endregion
        

        #region deletgate


        #endregion

        #region Safe Methods

        #region KeyBoard Or Mouse

        public static bool GetState(VirtualKeys Key)
        {
            return (Win32APIUnsafe.GetKeyState((int)Key) == 1);
        }

        public static void SetState(VirtualKeys Key, bool State)
        {
            if (State != GetState(Key))
            {
                Win32APIUnsafe.keybd_event(
                                     (byte)Key,
                                      0x45,
                                      KEYEVENTF_EXTENDEDKEY | 0,
                                      0
                                     );
                Win32APIUnsafe.keybd_event(
                                     (byte)Key,
                                     0x45,
                                     KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                                     0
                                    );
            }

        }

        #endregion

        #region IE or Browser

        public static InternetExplorer OpenNewIe(string url, string postData)
        {
            var ie = new InternetExplorer();
            object vPost, vHeaders, vFlags, vTargetFrame;
            vPost = null;
            vFlags = null;
            vTargetFrame = null;
            vHeaders = "Content-Type: application/x-www-form-urlencoded" + Convert.ToChar(10) + Convert.ToChar(13);
            if (!string.IsNullOrEmpty(postData))
                vPost = ASCIIEncoding.ASCII.GetBytes(postData);
            ie.Visible = true;
            ie.Navigate(url, ref vFlags, ref vTargetFrame, ref vPost, ref vHeaders);
            return ie;
        }
         
        public static mshtml.IHTMLDocument2 GetIDoc2FromHandle(IntPtr handle)
        {
            object obj = new object();

            mshtml.IHTMLDocument2 doc;
            Guid guidIEDocument2 = typeof(mshtml.IHTMLDocument2).GUID; //获取mshtml.IHTMLDocument2接口GUID
            int tempInt = 0;
            uint WM_HTML_GETOBJECT = Win32APIUnsafe.RegisterWindowMessage("WM_HTML_GETOBJECT"); //注册WM_HTML_GETOBJECT消息 

            uint W = Win32APIUnsafe.SendMessageTimeout(handle, WM_HTML_GETOBJECT, 0, 0, 0x2, 1000, out tempInt);
            int result = Win32APIUnsafe.ObjectFromLresult(tempInt, ref IID_IHTMLDocument, 0, ref obj);

            //int w = Win32APIUnsafe.SendMessage(handle, WM_HTML_GETOBJECT, 0, ref tempInt);
            //int result = Win32APIUnsafe.ObjectFromLresult(w, ref guidIEDocument2, 0, ref obj);
            
            doc = (mshtml.IHTMLDocument2)obj;
            return doc;
        }

        public static int GetIEWindowDocument(string windowName)
        {
            //开始查找指定的ie窗体 
            return Win32APIUnsafe.FindWindow("Internet Explorer_Server", windowName);
        }

        public static IHTMLDocument2 GetIDoc2FromTitle(string title, out IntPtr hwnd)
        {
            hwnd = IntPtr.Zero;
            
            Process[] processes = Process.GetProcessesByName("iexplore");
            if (processes.Length > 0)
            { 
                foreach (Process cp in processes)
                {
                    hwnd = cp.MainWindowHandle;
                    Win32APIUnsafe.EnumProc proc = new Win32APIUnsafe.EnumProc(EnumWindows);
                    Win32APIUnsafe.EnumChildWindows(hwnd, proc, ref hwnd);
                    if (hwnd != IntPtr.Zero)
                    {
                        IHTMLDocument2 doc2 = GetIDoc2FromHandle(hwnd);
                        if (doc2!=null && doc2.title == title)
                        {
                            return doc2;
                        }
                    }
                }
               
            }

            return null;
        }

        private static int EnumWindows(IntPtr hWnd, ref IntPtr lParam)
        {
            int retVal = 1;
            StringBuilder classname = new StringBuilder(128);
            Win32APIUnsafe.GetClassName(hWnd, classname, classname.Capacity);
            /// check if the instance we have found is Internet Explorer_Server
            if ((bool)(string.Compare(classname.ToString(), "Internet Explorer_Server") == 0))
            {
                lParam = hWnd;
                retVal = 0;
            }
            return retVal;
        }
        #endregion

        #endregion
    }


    [Flags]
    public enum MouseEventFlag : uint
    {
        Move = 0x0001,
        LeftDown = 0x0002,
        LeftUp = 0x0004,
        RightDown = 0x0008,
        RightUp = 0x0010,
        MiddleDown = 0x0020,
        MiddleUp = 0x0040,
        XDown = 0x0080,
        XUp = 0x0100,
        Wheel = 0x0800,
        VirtualDesk = 0x4000,
        Absolute = 0x8000
    }

    public enum VirtualKeys : byte
    {
        VK_NUMLOCK = 0x90, //数字锁定键
        VK_SCROLL = 0x91,  //滚动锁定
        VK_CAPITAL = 0x14, //大小写锁定
        VK_A = 66,
        VK_DOWN = 0x28,
        VK_LBUTTON = 0x01,
        VK_RETURN = 0xD
    }
}
